import React from "react";
import { Tooltip, Row, Col } from "antd";
import { defaultComponentMapping } from "./constants/map";
import { transformData2GUI } from "./utils";
import { throttle, get } from "lodash";
export * from "./utils";
import "antd/dist/antd.css";
import "./index.less";

type GUIControlMapping = { [key: string]: any };
interface IVisbarGUIProps {
  config: any;
  value?: any;
  onChange?: (ev: any) => any;
  extensions?: GUIControlMapping;
}
interface IVisbarGUIState {
}
export default class VisbarGUI extends React.Component<IVisbarGUIProps, IVisbarGUIState> {
  static extensionControl: GUIControlMapping = {};
  constructor(props: IVisbarGUIProps) {
    super(props);
  }
  static register(extensions: GUIControlMapping) {
    this.extensionControl = Object.assign({}, this.extensionControl, extensions);
  }
  getComponentNode = (key) => {
    const { extensions } = this.props;
    return (extensions || {})[key] || VisbarGUI.extensionControl[key] || defaultComponentMapping[key];
  }
  handleOnChange = (value, node) => {
    const { onChange } = this.props;
    onChange && onChange({ value, path: node.path, key: node.key})
  }
  throttleHandleChange = throttle(this.handleOnChange, 100);
  renderComponent = (data = [], value?: any) => {
    value = value ? value : this.props.value;
    return data.map(node => {
      const Node = this.getComponentNode(node.node);
      if (!Node) return null;
      if(node.node === "array") return <Node {...node} value={get(value, node.path)} getComponent={this.getComponentNode} onChange={(value) => this.throttleHandleChange(value, node)} />
      if (node.children) return <Node {...node} key={node.key} className="visbar-gui-item">{ this.renderComponent(node.children) }</Node>
      if (node.node === "suite") return <Node {...node} Node={this.getComponentNode(node.trulyNode)} onChange={(value) => this.throttleHandleChange(value, node)} />
      return (<Row className="visbar-gui-item visbar-gui-leaf-item" key={node.key}>
          <Col span={6} className="visbar-gui-item-label">
            <Tooltip title={node.description || node.name}>
              <label>{node.name}</label>
            </Tooltip>
          </Col>
          <Col span={18}>
            <Node {...node} value={get(value, node.path)} onChange={(value) => this.throttleHandleChange(value, node)} />
          </Col>
        </Row>)
    })
  }
  render() {
    const { config } = this.props;
    return (<div className="visbar-gui-container">
      {this.renderComponent(transformData2GUI(config))}
   </div>) 
  }
}